package cz.patamat.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cz.patamat.support.EmailDataStorage;
import cz.patamat.support.PromowebAnswerSheet;

/**
 * Store answer sheet response. 
 *
 */
@SuppressWarnings("serial")
public class AddAnswerSheetResponseServlet extends HttpServlet {
	
	private EmailDataStorage emailDataStorage = new EmailDataStorage();
	
	/**
	 * Get operation is not supported so redirect to promotion web page.
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.getRequestDispatcher(ShowProtowebServlet.PROMOWEB_URL).forward(req, resp);
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String question1AnswerId = req.getParameter("q1");
		String question2AnswerId = req.getParameter("q2");
		String[] question3AnswerIds = getQuestion3AnswerIds(req);
		String question4AnswerId = req.getParameter("q4");
		PromowebAnswerSheet promowebAnswerSheet = new PromowebAnswerSheet();
		promowebAnswerSheet.respondQuestion1(question1AnswerId);
		promowebAnswerSheet.respondQuestion2(question2AnswerId);
		promowebAnswerSheet.respondQuestion3(question3AnswerIds);
		promowebAnswerSheet.respondQuestion4(question4AnswerId);
		
		emailDataStorage.saveAnswerSheetResponse(promowebAnswerSheet.responsesToString());
		
		req.setAttribute("successAnswerSheetResponse", true);
		req.getRequestDispatcher(ShowProtowebServlet.PROMOWEB_URL).forward(req, resp);
	}

	private String[] getQuestion3AnswerIds(HttpServletRequest req) {
		List<String> question3AnswerIds = new ArrayList<String>();
		
		if (getCheckboxInputValue(req, "q3_a1")) {
			question3AnswerIds.add("a1");
		}
		if (getCheckboxInputValue(req, "q3_a2")) {
			question3AnswerIds.add("a2");
		}
		if (getCheckboxInputValue(req, "q3_a3")) {
			question3AnswerIds.add("a3");
		}
		if (getCheckboxInputValue(req, "q3_a4")) {
			question3AnswerIds.add("a4");
		}
		if (getCheckboxInputValue(req, "q3_a5")) {
			question3AnswerIds.add("a5");
		}
		return question3AnswerIds.toArray(new String[question3AnswerIds.size()]);
	}
	
	private boolean getCheckboxInputValue(HttpServletRequest req, String paramName) {
		String paramValue = req.getParameter(paramName);
		if (paramValue == null) {
			return false;
		}
		if (("ON").equals(paramValue.toUpperCase())) {
			return true;
		}
		return false;
	}

}
